package com.wennimei.service;

import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.methods.GetMethod;
import org.springframework.stereotype.Service;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.wennimei.domain.Picture;
import com.wennimei.enums.MessageTypeEnum;

@Service
public class PictureSearchService {

    @SuppressWarnings("unchecked")
    public List<Picture> get(String content) {
        content = content.replaceAll(
                MessageTypeEnum.PICTURE_SEARCH.getReplaceRegx(), "");
        int rn = (int) (Math.random() * 3) + 3;
        int pn = (int) (Math.random() * 3) + 1;
        String url = "http://image.baidu.com/i?tn=baiduimagejson&word=%s&rn=%s&pn=%s";
        String json;
        try {
            HttpClient client = new HttpClient();
            GetMethod get = new GetMethod(String.format(url,
                    URLEncoder.encode(content, "gb18030"), rn, pn));
            client.executeMethod(get);
            int status = 0;
            if ((status = get.getStatusCode()) != HttpStatus.SC_OK)
                throw new Exception("http status error:" + status);
            json = new String(
                    get.getResponseBodyAsString().getBytes("gb18030"),
                    "gb18030");
        } catch (Exception e) {
            return null;
        }
        Gson gson = new Gson();
        Map<String, Object> map = gson.fromJson(json,
                new TypeToken<Map<String, Object>>() {}.getType());
        List<Map<String, String>> objs = (List<Map<String, String>>) map
                .get("data");

        List<Picture> res = new ArrayList<Picture>();
        for (Map<String, String> m: objs) {
            if (null == m || m.size() == 0)
                continue;
            Picture picture = new Picture(m.get("fromPageTitleEnc").replaceAll(
                    "<[^>]+>", ""), m.get("fromPageTitleEnc").replaceAll(
                    "<[^>]+>", ""), m.get("objURL"), m.get("objURL"));
            res.add(picture);
        }

        return res;
    }
}
